package team.chuangshu.lm.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import team.chuangshu.lm.base.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther zhang
 * @ TO DO
 * @creatTime 2019/5/9 21:15
 **/
@Component
@Slf4j
public class AuthenticationFailureHandler extends ExceptionMappingAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败!");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");

        //response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));
        JSONObject jsonObject = JSONObject.fromObject(ResultUtil.Error("500","用户名不存在或密码错误"));
        log.info(jsonObject.toString());
        response.getWriter().write(jsonObject.toString());
        //response.getWriter().write("mes: error");
        //response.sendRedirect("html/index.html");
        //throw new IOException(exception);
    }
}